package com.ja.openchat.ui.contact;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.blankj.utilcode.util.SizeUtils;
import com.google.gson.JsonObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.FragmentContactBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.message.AddContactActivity;
import com.ja.openchat.ui.message.ScanActivity;
import com.ja.openchat.viewmodels.ContactViewModel;
import com.ja.openchat.views.ScaleTransitionPagerTitleView;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class ContactFragment extends BaseFragment<FragmentContactBinding, ContactViewModel> {

    private ContactListFragment contactListFragment;
    private GroupListFragment groupListFragment;
    List<String> mDataList = new ArrayList<>();
    private MobileContactFragment mbContactFragment;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_contact;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public void initView() {
        super.initView();
        mDataList.add(getString(R.string.friend_text));
        mDataList.add(getString(R.string.group_text));
        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
        if(configInfo==null||configInfo.can_see_address_book){
            mDataList.add(getString(R.string.address_book));
        }
        initMagicIndicator();

        binding.ivBarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(getActivity())
                        .offsetY(SizeUtils.dp2px(25))
                        .hasShadowBg(false)
                        .atView(binding.ivBarRight)
                        .asAttachList(new String[]{getString(R.string.add_friend_text), getString(R.string.create_group), getString(R.string.create_prive_chat), getString(R.string.scan_text)}
                                , new int[]{R.mipmap.image_add_buddy, R.mipmap.image_add_group, R.mipmap.private_chat, R.mipmap.image_scan},
                                (position, text) -> {
                                    switch (position) {
                                        case 0:
                                            startActivity(AddContactActivity.class);
                                            break;
                                        case 1:
                                            ContactChooseActivity.startWithCreateSuperGroup(getActivity());
                                            break;
                                        case 2:
                                            ContactChooseActivity.start(getActivity(), ContactChooseActivity.ContactChooseType.ContactChooseType_CreateSecreat);
                                            break;
                                        case 3: {
                                            IntentIntegrator integrator = new IntentIntegrator(getActivity());
                                            integrator.setPrompt("");
                                            integrator.setBeepEnabled(false);
                                            integrator.setBarcodeImageEnabled(false);
                                            integrator.setOrientationLocked(false);
                                            integrator.setCaptureActivity(ScanActivity.class);
                                            integrator.initiateScan();
                                        }
                                        break;
                                    }
                                },R.layout.dialog_attach_list_popu,R.layout.dialog_attach_item).show();
            }
        });
    }


    private void initMagicIndicator() {
        MagicIndicator magicIndicator = binding.magicIndicator;
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(Color.BLACK);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setTextSize(24);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        binding.viewPager.setCurrentItem(index);
                    }
                });
                simplePagerTitleView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
                    @Override
                    public void onViewAttachedToWindow(View v) {
//                        simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    }

                    @Override
                    public void onViewDetachedFromWindow(View v) {

                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setRoundRadius(UIUtil.dip2px(context, 3));
                indicator.setYOffset(UIUtil.dip2px(context, 3));
                indicator.setColors(Color.BLACK);
                return indicator;
            }

            public float getTitleWeight(Context context, int index) {
                if (index == 0) {
                    return 3.0f;
                } else if (index == 1) {
                    return 1.2f;
                } else {
                    return 1.0f;
                }
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        binding.viewPager.setAdapter(new FragmentPagerAdapter(getFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                if (position == 0) {
                    if (contactListFragment == null)
                        contactListFragment = new ContactListFragment();
                    return contactListFragment;
                } else if (position == 1) {
                    if (groupListFragment == null)
                        groupListFragment = new GroupListFragment();
                    return groupListFragment;
                } else {
                    if (mbContactFragment == null)
                        mbContactFragment = new MobileContactFragment();
                    return mbContactFragment;
                }
            }

            @Override
            public int getCount() {
                return mDataList.size();
            }
        });
        ViewPagerHelper.bind(magicIndicator, binding.viewPager);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x110 && data != null){
            UserInfo userInfo = (UserInfo)data.getParcelableExtra("user");
            if(userInfo!=null){
                TelegramManager.getTelegramManager().createPrivateChat(getContext(), userInfo.id, new TgResultBlock<ChatInfo>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                        if (obj != null) {
                            ChatActivity.startActivity(getContext(), obj);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        ToastUtils.showShort(getString(R.string.request_error));
                    }
                });
            }
        }
    }
}